const util = require("../../utils/util.js");

Page({
  data: {
    team: -1,
    wel: "欢迎加入路飞日程",
    weeks: [
      { "id": "1", "name": "一" },
      { "id": "2", "name": "二" },
      { "id": "3", "name": "三" },
      { "id": "4", "name": "四" },
      { "id": "5", "name": "五" },
      { "id": "6", "name": "六" },
      { "id": "7", "name": "日" }],
    time: util.ftime(new Date()),
    date: util.fdate(new Date()),
    users: wx.getStorageSync("USERS"),
    showMonth: {},
    data: {},
    selectDateText: '',
    pickerDateValue: '',
    // 事项列表
    itemList: []
  },
  onReady() { },
  onLoad(options) {
    util.showLoading();
    this.onHideTabBar();
    this.onLogin();
  },
  onShow: function (e) {
    this.onTeam();
  },
  onHideTabBar: function () {
    if (this.data.team && (this.data.team == -1 || this.data.team == 0)) {
      wx.hideTabBar({});
    }
  },
  onLogin: function (e) {//登录处理
    var that = this;
    var hasLogin = false;
    wx.checkSession({
      success: function (options) {
        if (options.errMsg == "checkSession:ok") {
          wx.getStorage({
            key: 'USERS',
            success: function (res) {
              that.setData({
                users: res.data
              });
              if (that.data.users.id) {
                hasLogin = true;
              }
            }
          })
        }
      }
    });
    if (!hasLogin) {
      wx.login({
        success: function (options) {
          if (options.code) {
            util.wxPost({
              url: "/rest/lufei/login", params: { "code": options.code },
              success: function (res) {
                that.setData({
                  users: res.data.data
                });
                wx.setStorage({
                  key: "USERS",
                  data: res.data.data
                });
                hasLogin = true;
              }
            });
          }
        },
        fail: function () {
          util.log("登录想睡觉了");
        }
      });
    }
  },
  onTeam: function (e) {//获取团队
    var that = this;
    var interval = setInterval(function () {
      var uclean = wx.getStorageSync("USERSClean");
      if (uclean) {
        that.onLogin();
        that.onHideTabBar();
        that.setData({
          users : []
        });
        wx.removeStorageSync("USERSClean");
      }
      if (that.data.users && that.data.users.id) {
        clearInterval(interval);
        that.setData({
          team: that.data.users.teamId
        });
        if (that.data.team && that.data.team > 0) {
          wx.showTabBar({});
          changeDate.call(that);
        }
      } else {
        wx.getStorage({
          key: 'USERS',
          success: function (res) {
            that.setData({
              users: res.data
            });
          },
        })
      }
    }, 1 * 1000);
  },
  onWorkDate:function(e){
    var that = this;
    const { year, month, date } = that.data.data.selected;
    var $date = new Date(year, month - 1, date);
    wx.setStorage({
      key: 'onWorkDate',
      data: util.fdate($date, "YYYY-MM-DD")
    });
  },
  onApplys: function (e) {//申请团队
    wx.navigateTo({
      url: '/pages/index/apply'
    })
  },
  onScan: function (e) {//扫码加入
    var that = this;
    var interval = setInterval(function () {
      if (that.data.users.id) {
        clearInterval(interval);
        wx.scanCode({
          success: function (res) {
            if (res.errMsg == "scanCode:ok") {
              var data = JSON.parse(res.result).data;
              var params = {
                "tid": data.id,
                "uid": that.data.users.id
              }
              util.wxPost({
                url: "/rest/lufei/joinTeams", params: params,
                success: function (res) {
                  util.hideToast();
                  if (res.data.status == "000") {
                    var users = that.data.users;
                    users.teamId = params.tid;
                    wx.setStorage({
                      key: 'USERS',
                      data: users,
                      success: function () {
                        that.onLoad();
                      }
                    });
                  } else {
                    wx.showToast({
                      title: "加入团队失败!",
                      icon: "failure",
                      duration: 1500
                    });
                  }
                }
              });
            }
          }
        });
      } else {
        that.onLogin();
      }
    }, 1 * 10);
  },
  datePickerChangeEvent(e) {
    var date = new Date(Date.parse(e.detail.value));
    changeDate.call(this, new Date(date.getFullYear(), date.getMonth(), 1));
  },
  changeDateEvent(e) {
    util.showLoading();
    const { year, month } = e.currentTarget.dataset;
    changeDate.call(this, new Date(year, parseInt(month) - 1, 1));
  },
  dateClickEvent(e) {
    util.showLoading();
    const { year, month, date } = e.currentTarget.dataset;
    const { data } = this.data;
    let selectDateText = '';
    data['selected']['year'] = year;
    data['selected']['month'] = month;
    data['selected']['date'] = date;
    this.setData({ data: data });
    changeDate.call(this, new Date(year, parseInt(month) - 1, date));
  }
});
function loadItemListData() {//加载事项列表数据
  const { year, month, date } = this.data.data.selected;
  var that = this;
  var $date = new Date(year, month - 1, date);
  var parmas = {
    "uid": that.data.users.id,
    "tid": that.data.users.teamId,
    "date": util.fdate($date, "YYYY-MM-DD")
  }
  if (parmas.uid && parmas.uid > 0 && parmas.tid && parmas.tid != "") {
    var isCache = false;
    var data = wx.getStorageSync(parmas.tid + ":home:" + parmas.date)
    if (data) {
      that.setData({
        itemList: data
      });
      isCache = true;
      util.hideToast();
    }
    if (!isCache) {
      util.wxPost({
        url: "/rest/lufei/weekUid", params: parmas,
        success: function (res) {
          var $data = res.data.data;
          if (res.data.status == "000") {
            if (!$data[0].partakeUsers) {
              $data = [];
            }
            wx.setStorage({
              key: parmas.tid + ":home:" + parmas.date,
              data: $data,
            })
            that.setData({
              itemList: $data
            });
            util.hideToast();
          }
        }
      });
    }
  }
}

function changeDate(targetDate) {//变更日期数据
  let date = targetDate || new Date();
  let currentDateObj = new Date();
  let showMonth, //当天显示月份
    showYear, //当前显示年份
    showDay, //当前显示星期
    showDate, //当前显示第几天
    showMonthFirstDateDay, //当前显示月份第一天的星期
    showMonthLastDateDay, //当前显示月份最后一天的星期
    showMonthDateCount; //当前月份的总天数
  let data = [];
  showDate = date.getDate();
  showMonth = date.getMonth() + 1;
  showYear = date.getFullYear();
  showDay = date.getDay();
  showMonthDateCount = new Date(showYear, showMonth, 0).getDate();
  date.setDate(1);
  showMonthFirstDateDay = date.getDay(); //当前显示月份第一天的星期
  date.setDate(showMonthDateCount);
  showMonthLastDateDay = date.getDay(); //当前显示月份最后一天的星期  
  let beforeDayCount = 0,
    beforeYear, //上页月年份
    beforMonth, //上页月份
    afterYear, //下页年份
    afterMonth, //下页月份
    afterDayCount = 0, //上页显示天数
    beforeMonthDayCount = 0; //上页月份总天数
  //上一个月月份
  beforMonth = showMonth === 1 ? 12 : showMonth - 1;
  //上一个月年份
  beforeYear = showMonth === 1 ? showYear - 1 : showYear;
  //下个月月份
  afterMonth = showMonth === 12 ? 1 : showMonth + 1;
  //下个月年份
  afterYear = showMonth === 12 ? showYear + 1 : showYear;

  //获取上一页的显示天数
  if (showMonthFirstDateDay != 0)
    beforeDayCount = showMonthFirstDateDay - 1;
  else
    beforeDayCount = 6;
  //获取下页的显示天数
  if (showMonthLastDateDay != 0)
    afterDayCount = 7 - showMonthLastDateDay;
  else
    showMonthLastDateDay = 0;
  //如果天数不够6行，则补充完整
  let tDay = showMonthDateCount + beforeDayCount + afterDayCount;
  if (tDay <= 35)
    afterDayCount += (42 - tDay); //6行7列 = 42
  let selected = this.data.data['selected'] || { year: showYear, month: showMonth, date: showDate };
  let selectDateText = selected.year + '年' + util.formatNumber(selected.month) + '月' + util.formatNumber(selected.date) + '日';

  data = {
    currentDate: currentDateObj.getDate(), //当天日期第几天
    currentYear: currentDateObj.getFullYear(), //当天年份
    currentDay: currentDateObj.getDay(), //当天星期
    currentMonth: currentDateObj.getMonth() + 1, //当天月份
    showMonth: showMonth, //当前显示月份
    showDate: showDate, //当前显示月份的第几天 
    showYear: showYear, //当前显示月份的年份
    beforeYear: beforeYear, //当前页上一页的年份
    beforMonth: beforMonth, //当前页上一页的月份
    afterYear: afterYear, //当前页下一页的年份
    afterMonth: afterMonth, //当前页下一页的月份
    selected: selected,
    selectDateText: selectDateText
  };

  let dates = [];
  let _id = 0; //为wx:key指定

  if (beforeDayCount > 0) {
    beforeMonthDayCount = new Date(beforeYear, beforMonth, 0).getDate();
    for (let fIdx = 0; fIdx < beforeDayCount; fIdx++) {
      dates.unshift({
        _id: _id,
        year: beforeYear,
        month: beforMonth,
        date: beforeMonthDayCount - fIdx
      });
      _id++;
    }
  }

  for (let cIdx = 1; cIdx <= showMonthDateCount; cIdx++) {
    dates.push({
      _id: _id,
      active: (selected['year'] == showYear && selected['month'] == showMonth && selected['date'] == cIdx), //选中状态判断
      year: showYear,
      month: showMonth,
      date: cIdx
    });
    _id++;
  }

  if (afterDayCount > 0) {
    for (let lIdx = 1; lIdx <= afterDayCount; lIdx++) {
      dates.push({
        _id: _id,
        year: afterYear,
        month: afterMonth,
        date: lIdx
      });
      _id++;
    }
  }
  data.dates = dates;
  this.setData({ data: data, pickerDateValue: showYear + '-' + showMonth });
  loadItemListData.call(this);
}
